package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Food;
import com.itheima.service.FoodService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/food")
public class FoodController {
    @Reference
    private FoodService foodService;
    @PreAuthorize("hasAuthority('FOOD_QUERY')")
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult=foodService.findPage(
                queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString()
        );
        return pageResult;
    }
    @PreAuthorize("hasAuthority('FOOD_ADD')")
    @RequestMapping("/add")
    public Result add(@RequestBody Food food){
        try{
            foodService.add(food);
            return new Result(true, MessageConstant.FOOD_ADD_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.FOOD_ADD_FAIL);
        }
    }
    @PreAuthorize("hasAuthority('FOOD_QUERY')")
    @RequestMapping("/findById")
    public Food findById(Integer id){
        return foodService.findById(id);
    }
    @PreAuthorize("hasAuthority('FOOD_EDIT')")
    @RequestMapping("edit")
    public Result edit(@RequestBody Food food){
        try{
            foodService.edit(food);
            return new Result(true,MessageConstant.FOOD_EDIT_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.FOOD_EDIT_FAIL);
        }
    }
    @PreAuthorize("hasAuthority('FOOD_DELETE')")
    @RequestMapping("/deleteById")
    public Result deleteById(Integer id){
        try{
            foodService.deleteById(id);
            return new Result(true,MessageConstant.FOOD_DELETE_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.FOOD_DELETE_FAIL);
        }
    }
}
